package com.dz.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

// 全局异常捕获处理器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody  // 返回结果封装为json
@Slf4j
public class GlobalExceptionHandler {
    // 处理 SQLIntegrityConstraintViolationException 的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        String errorMsg = "未知错误";
        // contains() 填写所报错的内容
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            errorMsg = "用户账号：" + split[2] + "已存在";
            return R.error(errorMsg);
        }
        return R.error(errorMsg);
    }

    /**
     * 处理删除菜品分类时的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }
}
